import {addQuestionBankUsingPost, delImgUsingPost, uploadImgUsingPost} from '@/api/questionBankController';
import { ProColumns, ProTable } from '@ant-design/pro-components';
import { message, Modal } from 'antd';
import { UploadOutlined, DeleteOutlined } from '@ant-design/icons';
import React from 'react';

interface Props {
  visible: boolean;
  columns: ProColumns<API.QuestionBank>[];
  onSubmit: (values: API.QuestionBankAddRequest) => void;
  onCancel: () => void;
}

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.QuestionBankAddRequest) => {
  const hide = message.loading('正在添加');
  try {
    await addQuestionBankUsingPost(fields);
    hide();
    message.success('创建成功');
    return true;
  } catch (error: any) {
    hide();
    message.error('创建失败，' + error.message);
    return false;
  }
};

const handleUploadAvatar = async (file: any, form: any) => {
  const hide = message.loading('正在上传');
  try {
    const { data, code } = await uploadImgUsingPost({}, {}, file);
    hide();
    if (code === 0) {
      message.success('上传成功');
      form.setFieldsValue({ picture: data }); // 更新表单中的图片字段
    } else {
      message.error('上传失败');
    }
  } catch (error: any) {
    hide();
    message.error('上传失败，' + error.message);
  }
};

const handleDeleteAvatar = async (form: any) => {
  Modal.confirm({
    title: '确认删除图片',
    content: '删除后图片将无法使用，需重新上传',
    okText: '删除',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      const hide = message.loading('正在删除');
      try {
        await delImgUsingPost({ img: form.getFieldValue('picture')});
        hide();
        message.success('删除成功');
        form.setFieldsValue({ picture: '' }); // 更新表单中的图片字段
      } catch (error: any) {
        hide();
        message.error('删除失败，' + error.message);
      }
    },
    onCancel() {
      console.log('取消删除');
    },
  });
};

/**
 * 创建弹窗
 * @param props
 * @constructor
 */
const CreateModal: React.FC<Props> = (props) => {
  const { visible, columns, onSubmit, onCancel } = props;

  return (
    <Modal
      destroyOnClose
      title={'创建'}
      open={visible}
      footer={null}
      onCancel={() => {
        onCancel?.();
      }}
    >
      <ProTable
        type="form"
        columns={[
          {
            title: '图片',
            dataIndex: 'picture',
            valueType: 'text',
            renderFormItem: (_, { defaultRender, ...rest }, form) => (
              <div>
                {form.getFieldValue('picture') && (
                  <img src={form.getFieldValue('picture')} alt="image" width="64" />
                )}
                <UploadOutlined
                  style={{ cursor: 'pointer', marginLeft: 8 }}
                  onClick={() => {
                    const input = document.createElement('input');
                    input.type = 'file';
                    input.accept = 'image/*';
                    input.onchange = (e: any) => {
                      const file = e.target.files[0];
                      if (file) {
                        handleUploadAvatar(file, form);
                      }
                    };
                    input.click();
                  }}
                />
                {form.getFieldValue('picture') && (
                  <DeleteOutlined
                    style={{ cursor: 'pointer', marginLeft: 8 }}
                    onClick={() => handleDeleteAvatar(form)}
                  />
                )}
              </div>
            ),
          },
          ...columns,
        ]}
        onSubmit={async (values: API.QuestionBankAddRequest) => {
          const success = await handleAdd(values);
          if (success) {
            onSubmit?.(values);
          }
        }}
      />
    </Modal>
  );
};
export default CreateModal;
